<?php

/**
 * This is the model class for table "TopicExt".
 *
 * The followings are the available columns in table 'TopicExt':
 * @property integer $id
 * @property integer $tid
 * @property integer $ext_id
 * @property string $type
 * @property integer $weight
 */
class TopicExt extends CActiveRecord
{
    const TYPE_VIDEO = 'video';
    const TYPE_TASK = 'task';

    /**
     * @return string the associated database table name
     */
    public function tableName()
    {
        return 'topic_ext';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules()
    {
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
        return array(
            array('tid, ext_id', 'numerical', 'integerOnly' => true),
// The following rule is used by search().
            array('id, tid, ext_id,type,weight', 'safe', 'on' => 'search'),
            array('time_begin,time_end,searchKey', 'safe'),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations()
    {
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
        return array(
            'Video' => array(self::HAS_ONE, 'Video', ['id' => 'ext_id']),
            'Task' => array(self::HAS_ONE, 'Task', ['id' => 'ext_id']),

        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
            'id' => 'ID',
            'tid' => 'Tid',
            'ext_id' => 'ext_id',
            'type' => 'type',
            'weight' => 'weight',
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     *
     * Typical usecase:
     * - Initialize the model fields with values from filter form.
     * - Execute this method to get CActiveDataProvider instance which will filter
     * models according to data in model fields.
     * - Pass data provider to CGridView, CListView or any similar widget.
     *
     * @return CActiveDataProvider the data provider that can return the models
     * based on the search/filter conditions.
     */
    public function search()
    {
// @todo Please modify the following code to remove attributes that should not be searched.

        $criteria = new CDbCriteria;

        $criteria->compare('id', $this->id);
        $criteria->compare('tid', $this->tid);
        $criteria->compare('ext_id', $this->ext_id);
        $criteria->compare('type', $this->type);

        return new CActiveDataProvider($this, array(
            'criteria' => $criteria,
        ));
    }

    public static function getDb(Topic $topic)
    {
// @todo Please modify the following code to remove attributes that should not be searched.

        $criteria = new CDbCriteria;
        $criteria->compare('tid', $topic->id);
        $criteria->order = 'weight desc';

        return new CActiveDataProvider(self::class, array(
            'criteria' => $criteria,
        ));
    }

    public static function getExtDb(Topic $topic, $type, $in = false)
    {

        $extids = array_map(function (TopicExt $ext) use ($type) {
            if ($ext->type == $type) {
                return $ext->ext_id;
            }
            return 0;
        }, $topic->topicExts);
        $criteria = new CDbCriteria();
        $class = null;
        switch ($type) {
            case self::TYPE_VIDEO:
                if ($topic->taskId) {
                    $criteria->addColumnCondition(['task_id' => $topic->taskId,]);
                }

                if (!$in) {
                    $criteria->addNotInCondition('id', $extids);
                } else {
                    $criteria->addInCondition('id', $extids);
                }
                $class = Video::class;
                break;
            case self::TYPE_TASK:
                if (!$in) {
                    $criteria->addNotInCondition('id', $extids);
                } else {
                    $criteria->addInCondition('id', $extids);
                }
                $class = Task::class;

                break;
        }
        $criteria->compare('name', $topic->searchKey, true);
        $criteria->order = 'time_create desc';
        return new CActiveDataProvider($class, array(
            'criteria' => $criteria,
        ));
    }


    public static function build($tid, $ext_id, $type, $weight = null)
    {
        $model = new self();
        $model->tid = $tid;
        $model->ext_id = $ext_id;
        $model->type = $type;
        if ($weight === null) {
            $weight = self::getMaxWeight($tid);
            if (!$weight) {
                $weight = 0;
            }
            $weight++;
        }
        $model->weight = $weight;
        return $model;
    }

    public static function getMaxWeight($tid)
    {
        $sql = 'select max(weight) as max';
        $sql .= ' from ' . self::tableName();
        $sql .= ' where tid=:tid ';
        $result = Yii::app()->getDb()->createCommand($sql)->query([':tid' => $tid]);
        return $result->read()['max'];
    }

    public static function getMinWeight($tid)
    {
        $sql = 'select min(weight) as min';
        $sql .= ' from ' . self::tableName();
        $sql .= ' where tid=:tid ';
        $result = Yii::app()->getDb()->createCommand($sql)->query([':tid' => $tid]);
        return $result->read()['min'];
    }

    /**
     * Returns the static model of the specified AR class.
     * Please note that you should have this exact method in all your CActiveRecord descendants!
     * @param string $className active record class name.
     * @return TopicExt the static model class
     */
    public static function model($className = __CLASS__)
    {
        return parent::model($className);
    }

    public function isVideo()
    {
        return $this->type == self::TYPE_VIDEO;
    }

    public function getVideos($page, $size)
    {
        if ($this->isVideo()) {
            return [Video::model()->findByPk($this->ext_id)];
        } else {
            return Task::getVideos($this->ext_id, $page, $size);
        }
    }

    public function getItemContent()
    {
        $content =
            ' <div type="'.$this->type.'" id='.$this->ext_id.'  class="item_data panel-heading">类型:' . (!$this->isVideo()?'采集任务':'视频') .
            '</div>
                 <div class="panel-body">' . ($this->isVideo() ? $this->Video->name : $this->Task->name) . '</div>';
        return $content;
    }


}
